<?php

namespace app\devices\controller\api;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\AddShortUrlResponseBody\data;
use app\data\service\DataService;
use app\data\service\UserService;
use app\devices\service\BoxService;
use app\devices\service\DevicesService;
use app\devices\service\OrderService;
use app\devices\service\SocketService;
use app\wechat\service\WechatService;
use think\admin\Controller;
use think\cache\driver\Redis;
use think\Exception;

/**
 * APP数据接口
 * Class Index
 * @package app\data\controller\api
 */
class App extends Controller
{
    public function init(){
        $data = $this->_vali([
            'device_id.require' => '设备基板编号不能为空',
            'versionName.default' => '',
        ]);

        $redis = new Redis();
        $a = $redis->get("APPINIT".$data['device_id']);
        $num = $a[1]??0;
        $num = $num+1;
        $redis->set("APPINIT".$data['device_id'], [date("Y-m-d H:i:s"), $num], 60);

        $device = DevicesService::instance()->getDevice('', $data['device_id']);
        if(empty($device)){
            $this->error("初始化失败：未找到对应的设备");
        }

        $deviceService = new DevicesService($this->app);
        $fee = $deviceService->getDeviceFee($device['fee_id']);

        $deviceService->feeBuild($fee);

        $store = $deviceService->getStore($device['store_id']);

        $cabinet_num = BoxService::instance()->getBoxNum(['d_id'=>$device['id'], 'box_status'=>1, 'is_lock'=>1, 'user_type'=>0]);

        $qr_code_url = $device['qrcode']??'';
        if(empty($qr_code_url)){
            try{
                $wechat = WechatService::WeChatQrcode();
                $qr_code = $wechat->create(json_encode(['device_id'=>$data['device_id']],256));
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $qr_code_url = $wechat->url($qr_code['ticket']);
        }else{
            $qr_code_url = str_replace("https://img.haoda365.cn","http://img.haoda365.cn", $qr_code_url);
        }

        $redis->set("DevicesVersionName".$data['device_id'], $data['versionName']);

        $config = sysconf();
        $edition = $config['edition'];

        $logo = str_replace("https://img.haoda365.cn","http://img.haoda365.cn", $edition['logo']);

        $fee['fee_type'] = $fee['fee_type']=='免费'?$fee['fee_type']:$fee['fee_type'].'收费';

//        $device_name = explode(" ", $device['device_name']);
//
//        $device_id = substr($device['device_id'],-3);

        $this->success('成功',['d_id'=>$device['id'], 'business_hours'=>$store['bus_hours']?'全天':(substr($store['start_hours'],0,5).' - '.substr($store['end_hours'],0,5)), 'qr_code'=>$qr_code_url, 'fee_type'=>$fee['fee_type'], 'fee_rule'=>$fee['rule'], 'contact'=>$device['contact_number'], 'cabinet_num'=>$cabinet_num, 'device_name'=>$device['device_name'], 'logo'=>$logo]);
    }

    /**
     * 获取版本信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getVersion(){
        $config = sysconf();
        $version = $config['edition'];
        $version['versionCode'] = intval($version['versionCode']);

        $this->success('成功', $version);
    }

    /**
     * 注册用户
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function regForFace()
    {
        $data = $this->_vali([
            'face_id.require' => '人脸ID不能为空',
        ]);

        $user_id = $this->app->db->name("data_user")->where("face_id", $data['face_id'])->value('id');
        if(empty($user_id)){
            $user_id = $this->app->db->name("data_user")->insertGetId(['face_id'=>$data['face_id']]);
        }
        if (empty($user_id)) {
            $this->error("注册失败");
        }

        $redis = new Redis();
        $redis->handler()->ZADD('FaceIds', $user_id, $data['face_id']);

        $this->success("注册成功");
    }

//    /**
//     * 人脸识别开箱关箱
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\DbException
//     * @throws \think\db\exception\ModelNotFoundException
//     */
//    public function registerToFace(){
//        $data = $this->_vali([
//            'device_id.require' => '设备ID不能为空',
//            'face_id.require'   => '人脸ID不能为空',
//            'type.require'      => '行为类型不能为空',
//            'box_id.default'    => 0
//        ]);
//
//        $user_id = $this->app->db->name("data_user")->where("face_id", $data['face_id'])->value('id');
//        if(empty($user_id) && $data['type']==1){
//            $user_id = $this->app->db->name("data_user")->insertGetId(['face_id'=>$data['face_id']]);
//        }
//        if(empty($user_id) && $data['type']==2) {
//            $this->error("用户不存在");
//        }
//
//        $device = DevicesService::instance()->getDevice('',$data['device_id']);
//        if(empty($device)){
//            $this->error("设备不存在");
//        }
//
//        $redis = new Redis();
//        if($data['type']==1){
//            $boxs = $this->app->db->name("jcg_boxs")->where(["user_id"=>0, "d_id"=>$device['id']])->column("id, board_channel, device_board, box_num", 'id');
//            if(count($boxs)){
//                $box = $boxs[array_rand($boxs)];
//                $box['box_id'] = $box['id'];
//                $msg = ['type'=>2, 'device_id'=>$device['device_id'], 'ch'=>$box['board_channel'], 'device_board'=>$box['device_board']];
//                SocketService::instance()->sendSocket($msg);
//
//                $c_boxs = $redis->get("Box".$data['face_id'])??[];
//                $c_boxs[] = ['box_id'=>$box['box_id'], 'board_channel'=>$box['board_channel'], 'device_board'=>$box['device_board'], 'box_num'=>$box['box_num']];
//
//                $redis->set("Box".$data['face_id'], $c_boxs, 7200);
//
//                BoxService::instance()->updateBox($box['box_id'], ['user_id'=>1]);
//                $this->success("成功", ['tips'=>'柜门已打开，请放入物品关好柜门', 'box_num'=>($box['box_num']<10?'0'.$box['box_num']:$box['box_num'])]);
//            }else{
//                $this->app->db->name("jcg_boxs")->where(["user_id"=>1, "d_id"=>$device['id']])->update(['user_id'=>0]);
//                $this->error("柜子已满");
//            }
//        }else if($data['type']==2){
//            $boxs = $redis->get("Box".$data['face_id']);
//            if($boxs){
//                $box = $boxs[0];
//                $msg = ['type'=>2, 'device_id'=>$device['device_id'], 'ch'=>$box['board_channel'], 'device_board'=>$box['device_board']];
//                SocketService::instance()->sendSocket($msg);
//                unset($boxs[0]);
//                if($boxs){
//                    $boxs = array_merge($boxs);
//                    $redis->set("Box".$data['face_id'], $boxs, 7200);
//                }else{
//                    $redis->delete("Box".$data['face_id']);
//                }
//                BoxService::instance()->updateBox($box['box_id'], ['user_id'=>0]);
//                $this->success("成功", ['tips'=>'柜门已打开，请取出存储的物品并关好柜门', 'box_num'=>($box['box_num']<10?'0'.$box['box_num']:$box['box_num'])]);
//            }else {
//                $this->error("请先存包");
//            }
//        }
//    }

    /**
     * 选择要打开的箱格
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeBox(){
        $data = $this->_vali([
            'device_id.require' => '设备ID不能为空',
            'face_id.require'   => '人脸ID不能为空',
        ]);

        $user_id = $this->app->db->name("data_user")->where("face_id", $data['face_id'])->value('id');
        if(empty($user_id)) {
            $this->error("用户不存在");
        }

        $device = DevicesService::instance()->getDevice('',$data['device_id']);
        if(empty($device)){
            $this->error("设备不存在");
        }

        $boxs = $this->app->db->name("jcg_boxs")->where(["d_id"=>$device['id'], 'user_type'=>0])->fieldRaw("id as box_id, box_num, if(user_id>0,1,0) as status")->order("box_num ASC")->select();
        if(count($boxs)){
            $result = ['num'=>count($boxs), 'list'=>$boxs];
            $this->success("成功", $result);
        }else{
            $this->app->db->name("jcg_boxs")->where(["user_id"=>1, "d_id"=>$device['id']])->update(['user_id'=>0]);
            $this->error("柜子已满");
        }
    }

    /**
     * 存储
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function faceSaveBox(){
        $data = $this->_vali([
            'face_id.require'   => '人脸ID不能为空',
            'box_id.require'    => '箱子ID不能为空',
        ]);

        $user_id = $this->app->db->name("data_user")->where("face_id", $data['face_id'])->value('id');
        if(empty($user_id)) {
            $this->error("用户不存在");
        }

        $box = $this->app->db->name("jcg_boxs")->where(["id"=>$data['box_id']])->field("id, board_channel, device_board, box_num, d_id, user_id")->find();
        if(empty($box)){
            $this->error("箱子不存在");
        }else if($box['user_id']){
            $this->error("箱子已被TA人使用");
        }

        $device = DevicesService::instance()->getDevice($box['d_id']);
        if(empty($device)){
            $this->error("设备不存在");
        }

        $box['box_id'] = $box['id'];
        $msg = ['type'=>2, 'device_id'=>$device['device_id'], 'ch'=>$box['board_channel'], 'device_board'=>$box['device_board']];
        SocketService::instance()->sendSocket($msg);

        $redis = new Redis();
        $c_boxs = $redis->get("Box".$data['face_id'])??[];
        $c_boxs[] = ['box_id'=>$box['box_id'], "device_id"=>$device['device_id'], 'board_channel'=>$box['board_channel'], 'device_board'=>$box['device_board'], 'box_num'=>$box['box_num']];

        $redis->set("Box".$data['face_id'], $c_boxs, 86400*30);

        BoxService::instance()->updateBox($box['box_id'], ['user_id'=>$user_id]);
        $this->success("成功", ['tips'=>'柜门已打开，请放入物品关好柜门', 'box_num'=>($box['box_num']<10?'0'.$box['box_num']:$box['box_num'])]);
    }

    /**
     * 查看用户存储的箱格
     */
    public function faceBoxs(){
        $data = $this->_vali([
            'face_id.require'   => '人脸ID不能为空',
        ]);

        $redis = new Redis();
        $boxs = $redis->get("Box".$data['face_id'])??[];
        $list = [];
        if($boxs){
            foreach ($boxs as $row){
                $list[] = [
                    'box_id'=>$row['box_id'],
                    'box_num'=>$row['box_num'],
                ];
            }

        }

        $result = ['num'=>count($boxs), 'list'=>$list];
        $this->success('成功', $result);
    }

    /**
     * 打开用户指定的箱格
     * @throws \Exception
     */
    public function faceUnlock(){
        $data = $this->_vali([
            'face_id.require'   => '人脸ID不能为空',
            'box_id.require' =>'箱子ID不能为空',
        ]);

        $user_id = $this->app->db->name("data_user")->where("face_id", $data['face_id'])->value('id');
        if(empty($user_id)) {
            $this->error("用户不存在");
        }

        $redis = new Redis();
        $boxs = $redis->get("Box".$data['face_id'])??[];

        $res = 0;

        foreach ($boxs as $key=>$row){
            if($row['box_id']==$data['box_id']){
                $device_id=$row['device_id']??'';
                if(empty($device_id)){
                    $d_id = $this->app->db->name("jcg_boxs")->where("id", $row['box_id'])->value("d_id");
                    $device = DevicesService::instance()->getDevice($d_id);
                    $row['device_id'] = $device['device_id'];
                }
                $msg = ['type'=>2, 'device_id'=>$row['device_id'], 'ch'=>$row['board_channel'], 'device_board'=>$row['device_board']];
                SocketService::instance()->sendSocket($msg);
                unset($boxs[$key]);
                $res = 1;
            }
        }
        if($boxs){
            $boxs = array_merge($boxs);
            $redis->set("Box".$data['face_id'], $boxs, 86400*30);
        }else{
            $redis->delete("Box".$data['face_id']);
        }

        if($res){
            BoxService::instance()->updateBox($data['box_id'], ['user_id'=>0]);
            $this->success("成功", ['tips'=>'柜门已打开，请取出存储的物品并关好柜门', 'box_num'=>($row['box_num']<10?'0'.$row['box_num']:$row['box_num'])]);
        }else if($boxs){
            $this->error("柜门已经打开过了");
        }

        $this->error("所有箱子都已打开");
    }

    public function getBoxlist(){
        $data = $this->_vali([
            'd_id.require' => '设备ID不能为空',
            'mobile.require' => '手机号不能为空',
            'pick_up_code.require' => '取件码不能为空'
        ]);

        $redis = new Redis();

        $res = $redis->get("ClickGetBoxlist".$data['mobile']);
        if($res){
            $this->error("点击过快");
        }
        $redis->set("ClickGetBoxlist".$data['mobile'], 1,3);

        $user_ids = $this->app->db->name("data_user")->order('id DESC')->where("phone", $data['mobile'])->column('id');
        if(!$user_ids){
            $this->error("当前手机号未曾设置过取件码");
        }

        $picks = $this->app->db->name("jcg_device_pickupcode")->where("user_id", "in", $user_ids)->where(['used'=>0])->select();
        $picks = $picks->toArray();

        if(!empty($picks)) {
            $result = $return = [];
            $num = 0;
            foreach ($picks as $row){
                $order = OrderService::instance()->getCacheOrder($row['order_id']);
                $extends = json_decode($order['extends'], true);

                if($row['d_id']==$data['d_id'] && $row['code']==$data['pick_up_code']){
                    $temp_unlock = $half_hour = 0;
                    if(($extends['half_type']??0)==1 && $order['fee_type']==3){
                        $half_hour = $extends['half_hour']??0;
                        $temp_unlock = $half_hour<0.1 || $order['create_time']+ceil($half_hour*3600)>time()?1:0;
                    }else if($order['fee_type']==2 && ($extends['half_type']??0)==1){
                        $half_hour = $extends['half_hour']??0;
                        $half_hour = $half_hour<0.1?1:$half_hour;
                        $temp_unlock = $order['create_time']+ceil($half_hour*3600)>time()?1:0;
                    }
                    $min = intval($half_hour*60)-intval((time()-$order['create_time'])/60);
                    $last_half_hour = 0;
                    if($min>60){
                        $hour = intval($min/60);
                        if($hour>24){
                            $last_half_hour = intval($hour/24).'天'.intval($hour%24).'小时'.intval($min%60).'分';
                        }else{
                            $last_half_hour = $hour.'小时'.intval($min%60).'分';
                        }
                    }else{
                        $last_half_hour .= '分';
                    }
                    $box = [
                        'order_id'=>$row['order_id'],
                        'box_num'=>$row['box_num']<10?"0".$row['box_num']:$row['box_num'],
                        'box_type'=>$row['box_type'],
                        'temp_unlock'=>$temp_unlock,
                        'last_half_hour' => $min>0?$last_half_hour:""
                    ];
                    $num ++;
                    $result['return_code'] = 1;
                    $result['boxs'][] = $box;

                    $redis->set('order_id'.$row['order_id'], $row['id'], 300);
                }else if(empty($return) && $row['d_id']!=$data['d_id'] && $row['code']==$data['pick_up_code']){
                    $device_name = explode(" ",$extends['device_name']);

                    $return['device_name'] = $device_name[1]??'';
                    $return['box_type'] = $row['box_type']??'';
                    $return['box_num'] = ($row['box_num']<10?'0'.$row['box_num']:$row['box_num'])??'';
                    $return['title'] = "您的物品不在这个柜子！";
                    $return['temp_unlock'] = 0;

                    $return['summary'] = "请到 ".($device_name[1]??'')." 柜子去输入手机号和取件码取件";
                    $return['boxs'] = [];
                    $return['return_code'] = 0;
                    $return['num'] = 0;
                }
            }

            if(!$return && !$result){
                $this->error("取件码输入有误");
            }

            if($result){
                $result['num'] = $num;
            }

            $redis->delete("ClickGetBoxlist".$data['mobile']);
            $this->success("成功", $result?$result:$return);
        }else {
            $this->error("没有可以打开的存储柜");
        }
    }

    /**
     * 订单支付成功查询接口
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loading(){
        $data = $this->_vali([
            'order_id.require' => '订单ID不能为空',
        ]);
        $redis = new Redis();
        $order = $redis->get("order".$data['order_id']);
        if(empty($order)){
            $order = OrderService::instance()->get('', ['id'=>$data['order_id']]);
        }
        if(empty($order)){
            $this->error("订单不存在");
        }

        $cmd = $redis->handler()->ZRANK("UnLockCommand", $order['d_id'].'_'.$order['device_board'].'_'.$order['board_channel']);

        $open_cmd = $redis->handler()->ZRANK("OPENBOX", $order['d_id'].'_'.$order['device_board'].'_'.$order['board_channel']);
        if(is_numeric($cmd) && !is_numeric($open_cmd)){
            $this->error("失败");
        }else{
            $this->success("成功");
        }
    }

    /**
     * 手机号开锁
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function unlock(){
        $data = $this->_vali([
            'order_id.require' => '订单ID不能为空',
            'temp_unlock.default'=> 0
        ]);

        $temp_unlock = $data['temp_unlock'];
        unset($data['temp_unlock']);

        $redis = new Redis();

        $code_id = $redis->get("order_id".$data['order_id']);
        if(empty($code_id)){
            $this->success("当前没有可以打开的柜子");
        }

        $res = $redis->get("ClickUnLock".$data['order_id']);
        if($res){
            $this->error("点击过快");
        }
        $redis->set("ClickUnLock".$data['order_id'], 1,3);
        $order = OrderService::instance()->get('',['id'=>$data['order_id'], 'status'=>1]);
        if(empty($order)){
            $this->success("当前没有可以打开的柜子");
        }

        $box = BoxService::instance()->getBox($order['box_id']);
        if($box['is_lock']<1){
            $device = DevicesService::instance()->getDevice($order['d_id']);
            $msg = ['type'=>1, 'device_id'=>$device['device_id'], 'ch'=>$order['board_channel'], 'device_board'=>$order['device_board']];
            SocketService::instance()->sendSocket($msg);

            $box = BoxService::instance()->getBox($order['box_id']);
        }

        if(!($box['box_num']??0)){
            $this->error("箱格异常");
        }if($box['box_status']>2){
            $this->error("箱格处于".BoxService::instance()->box_status[$box['box_status']].'状态');
        }else if($box['user_id'] && $box['user_id']!=$order['user_id']){
            $this->error("箱格已被他人使用");
        }else if($box['is_lock']<1){
            $this->error("箱门已打开，请先关闭箱门");
        }else if($box['is_lock']==2){
            $this->error("箱格锁异常");
        }

        $extends = json_decode($order['extends'], true);

        $out_money = 0;
        $money = $order['money'];
        if($order['fee_type']==3){
            //使用金额
            $re_amount = ceil((time()-$order['create_time']-$order['free_hours']*3600)/3600)*$order['amount'];
            $re_amount = $re_amount>0?$re_amount:0;
            if(in_array($order['store_id'], OrderService::instance()->special_store) && $re_amount){
                $re_amount = $re_amount<2?2:$re_amount;
            }

            $max_money = $extends['max_money']??0;
            if($re_amount>$max_money){
                $re_amount = $max_money;
            }
            $out_money = OrderService::instance()->getRefund($order);
            if($order['money']<$re_amount && !$out_money){
                $this->error("订单已超时，请付款后再开锁");
            }else{
                //退款金额
                $order['refund'] = $order['money']-$re_amount;
                $money = $order['money']-$re_amount;
            }
        }

        $data['reality_end_time'] = time();

        $result = [
            'title' => '柜门已打开，请取走所有全部物品关好柜门',
            'order_no' => $order['order_no'],
            'box_num'=>$extends['box_num']<10?"0".$extends['box_num']:$extends['box_num'],
            'money' => sprintf("%.2f", $money),
            'times' => date("Y-m-d H:i",$order['create_time']), //.' - '.date("Y-m-d H:i", $data['reality_end_time']),
            'store_name'=>$extends['store_name']??'',
            'fee_type'=>$order['fee_type'],
            'box_type'=>$extends['box_type']??'',
        ];

        $half_hour = 0;
        if(($extends['half_type']??0)==1 && $order['fee_type']==3){
            $half_hour = $extends['half_hour']??0;
        }else if(($extends['half_type']??0)==1 && $order['fee_type']==2){
            $half_hour = $extends['half_hour']??0;
            $half_hour = $half_hour<0.1?1:$half_hour;
        }

        if($temp_unlock && ($extends['half_type']??0)!=1){
            $this->error('当前订单不可临时开门');
        }else if($temp_unlock && $order['fee_type']==2 && $half_hour>0 && $order['create_time']+ceil($half_hour*3600)<time()){
            $this->error('订单已超过可以中途开门的时间');
        }else if($temp_unlock && $order['fee_type']==3 && $half_hour>0 && $order['create_time']+ceil($half_hour*3600)<time()){
            $this->error('订单已超过可以中途开门的时间');
        }

        $this->app->db->startTrans();

        unset($data['order_id']);
        $data['reality_end_time'] = time();
        $data['status'] = 2;

        $res = 1;
        if($temp_unlock<1){
            try {
                if($order['fee_type']==3){
                    if($order['refund']>0){
                        $refund = OrderService::instance()->refund($order);
                        $extends['refund'] = $order['refund'];
                        if(is_array($refund)){
                            $data['out_refund_no'] = $refund['out_refund_no'];
                            if(empty($refund['out_refund_no'])){
                                $extends['refund_error'] = $refund['err_code_des'];
                            }
                            $data['extends'] = json_encode($extends,256);
                        }
                        $data['amount_total'] = $order['money']-$order['refund']+$out_money;
                    }else{
                        $data['amount_total'] = $order['money'] - $order['refund'];
                    }
                }else{
                    $data['amount_total'] = $order['money'];
                }

                $res_a = OrderService::instance()->endOrder($order['id'], $data);
                $res_b = BoxService::instance()->updateBox($order['box_id'], ['user_id'=>0, 'box_status'=>1]);
                $res_c = DevicesService::instance()->usePickUpCode(['order_id'=>$order['id'], 'user_id'=>$order['user_id']]);

                if($res_a && $res_b && $res_c){
                    $openid = UserService::instance()->getOpenid($order['user_id']);
                    if($openid){
                        OrderService::instance()->sendTemp(2, $openid, [$extends['device_name'], ($box['box_num']<10?'0'.$box['box_num']:$box['box_num']).'号', sprintf("%.2f", $data['amount_total']).'元', date("Y-m-d H:i", $order['create_time']), date("Y-m-d H:i")],"",'感谢你的使用！如有物品未取，请联系：'.($extends['store_contact']??''));

                        //添加redis 未关门提醒
                        $noLockMsg = [time(), 4, $openid, [$extends['device_name'], ($extends['box_num']<10?'0'.$extends['box_num']:$extends['box_num']).'号', date('Y-m-d H:i:s')]];
                        $redis->set($order['d_id'].'_'.$order['device_board'].'_'.$order['board_channel'], $noLockMsg, 22*60);
                    }

                    $this->app->db->commit();
                }else{
                    $this->app->db->rollback();
                    $res = 0;
                }
            }catch (\Exception $e){
                $this->app->db->rollback();
                $this->error("失败:".$e->getLine().",".$e->getMessage());
            }
        }
        if($res){
            $device = DevicesService::instance()->getDevice($order['d_id']);
            $msg = ['type'=>2, 'device_id'=>$device['device_id'], 'ch'=>$order['board_channel'], 'device_board'=>$order['device_board']];
            SocketService::instance()->sendSocket($msg);

            //添加redis 开锁命令
            $redis->handler()->ZADD("UnLockCommand", $order['user_id'], $order['d_id'].'_'.$order['device_board'].'_'.$order['board_channel']);

            if($temp_unlock<1){
                //删除超时定时任务对应订单缓存
                OrderService::instance()->clearOutTimeOrderCache($order);

                //移除已使用的箱子ID
                $redis->handler()->ZREM("orderUseBox".$order['d_id'], $order['box_id']);
            }
            $redis->delete("ClickUnLock".$order['id']);

            if($temp_unlock){
                $redis->set("TempLock".$order['id'], $order['id'], 30);
            }

            $conn = $temp_unlock?'临时开锁':"结束订单";

            jcgoplog('开锁','用户平板'.$conn.'开锁', UserService::instance()->getNickName($order['user_id']),$order['user_id'],$order['id'],$order['box_id']);

            $this->success('成功', $result);
        }else{
            $this->app->db->rollback();
            $this->error("失败1");
        }
    }

    /**
     * 未开锁（2小时内再次开锁）
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function re_unlock(){
        $data = $this->_vali([
            'order_id.require'     => '订单ID不能为空',
        ]);

        $order = OrderService::instance()->get('', ['id' => $data['order_id']]);
        if (empty($order)) {
            $this->error('读取订单失败');
        }

        $device = DevicesService::instance()->getDevice($order['d_id']);
        if(empty($device)){
            $this->error("设备不存在");
        }

        $redis = new Redis();
        $cmd = $redis->handler()->ZRANK("UnLockCommand", $order['d_id'].'_'.$order['device_board'].'_'.$order['board_channel']);
        if(!is_numeric($cmd)){
            $this->error("箱柜已经开启过了");
        }

        switch ($order['status']){
            case 0:
                $this->error('订单尚未支付');
                break;
        }

        $box = BoxService::instance()->getBox($order['box_id']);
        if($box['is_lock']<1){
            $msg = ['type'=>1, 'device_id'=>$device['device_id'], 'ch'=>$order['board_channel'], 'device_board'=>$order['device_board']];
            SocketService::instance()->sendSocket($msg, 1);
            $box = BoxService::instance()->getBox($order['box_id']);
        }else{
            $redis->handler()->ZREM("UnLockCommand", $order['d_id'].'_'.$order['device_board'].'_'.$order['board_channel']);
            $this->error("箱柜已经开启过了");
        }

        if(!($box['box_num']??0)){
            $this->error("箱格异常");
        }if($box['box_status']>2){
            $this->error("箱格处于".BoxService::instance()->box_status[$box['box_status']].'状态');
        }else if($box['user_id'] && $box['user_id']!=$order['user_id']){
            $this->error("箱格已被他人使用");
        }else if($box['is_lock']<1){
            $this->error("箱门已打开，请先关闭箱门");
        }else if($box['is_lock']==2){
            $this->error("箱格锁异常");
        }

        $boxs[] = $box??[];

        BoxService::instance()->buildData($boxs, $device['fee_id']);

        $msg = ['type'=>2, 'device_id'=>$device['device_id'], 'ch'=>$order['board_channel'], 'device_board'=>$order['device_board']];

        //再次开锁，直接推送命令
        SocketService::instance()->sendSocket($msg, 1);

        //添加redis 开锁命令
        $redis->handler()->ZADD("UnLockCommand", $order['user_id'], $order['d_id'].'_'.$order['device_board'].'_'.$order['board_channel']);

        $this->success("成功");
    }

    public function all(){
        $times = input("times",10);
        $msg = ['type'=>1, 'device_id'=>"NBSE88886666", "device_board"=>"00"];
        for ($i=0; $i<$times;$i++){
            SocketService::instance()->sendSocket($msg);
        }
    }
}